package com.cuitrip.business.webview;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.DownloadListener;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.cuitrip.apiservice.ServiceBusiness;
import com.cuitrip.business.home.IndexActivity;
import com.cuitrip.business.home.recommend.model.ShareCard;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.login.proxy.LoginProxy;
import com.cuitrip.business.share.ShareChannelBuilder;
import com.cuitrip.business.share.model.ServiceShareObject;
import com.cuitrip.business.share.ui.ShareDialogFragment;
import com.cuitrip.business.tripservice.CreateTripGuideActivity;
import com.cuitrip.business.tripservice.model.ServiceInfo;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.component.statelayout.StateLayout;
import com.cuitrip.service.R;
import com.lab.app.BaseActivity;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.image.process.MakeImageUtil;
import com.lab.jumper.Jumper;
import com.lab.logtrack.AppLog;
import com.lab.network.config.CtResponseCode;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.schemeurl.SchemeUrlHandler;
import com.lab.schemeurl.constant.Scheme;
import com.lab.utils.ArrayUtil;
import com.lab.utils.ToastUtil;
import com.umeng.common.message.Log;

import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by ak
 */
public class WebBrowserActivity extends CustomUiFragmentActivity implements View.OnClickListener {

    public static final String PARAM_WEB_PARAM = "param_web_param";
    public static final String PARAM_URL = "param_url";
    public static final String PARAM_OBJECT = "param_object";
    public static final String PARAM_WEB_TITLE = "PARAM_WEB_TITLE";
    public static final String PARAM_USE_WEB_TITLE = "PARAM_USE_WEB_TITLE";
    public static final String KEY_SHOW_TITLE = "show_title";
    public static final String ICON_SHARE_SHOW = "show_icon";
    public static final String PARA_SHARE_URL = "share_url";
    public static final String PARAM_SHARE_CARD = "share_card";


    private static final String TAG = "WebBrowserActivity";
    private static final int MAX_WEB_LOADING_PROGRESS = 100;
    @Bind(R.id.refresh_layout)
    protected SwipeRefreshLayout mRefreshLayout;
    @Bind(R.id.webView)
    protected WebView mWebView;
    protected String mStringObject;
    @Bind(R.id.state_layout)
    StateLayout mStateLayout;
    private String mUrl;
    private WebParam mWebParam;

    private WebHandler mWebHandler = new WebHandler(this);
    private String webTitle;
    private boolean useWebTitle;
    private boolean showTitleBar = true;
    private ShareDialogFragment shareDialogFragment;
    private ShareCard shareCard;
    private String shareTitle;
    private String shareContent;
    private String sharePic;
    private String shareUrl;
    private boolean shared;
    private String id;

    protected void onCreate(Bundle savedInstanceState) {
        Intent intent = getIntent();
        if (null != intent) {
            Bundle bundle = intent.getExtras();
            if (null != bundle) {
                mUrl = bundle.getString(PARAM_URL);
                mWebParam = bundle.getParcelable(PARAM_WEB_PARAM);
                mStringObject = bundle.getString(PARAM_OBJECT);
                webTitle = bundle.getString(PARAM_WEB_TITLE, "");
                useWebTitle = bundle.getBoolean(PARAM_USE_WEB_TITLE, false);
                showTitleBar = bundle.getBoolean(KEY_SHOW_TITLE, true);
                shareCard = (ShareCard) bundle.getSerializable(PARAM_SHARE_CARD);
            }
        }
        if (TextUtils.isEmpty(mUrl)) {
            Jumper.finishActivity(this);
            return;
        }
        super.onCreate(savedInstanceState, R.layout.web_browser_activity);
    }


    @Override
    public void initListener() {
        mStateLayout.setOnClickStateLayoutListener(new StateLayout.OnClickStateLayoutListener() {
            @Override
            public void onClick(StateLayout.State state) {
                reload();
            }
        });
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public void onTopbarRightPress() {
        if (shared) {
            navigateSharePage();
        } else {
            finish();
        }
    }

    public void navigateSharePage() {
        if (shareDialogFragment != null && shareDialogFragment.isShowing()) {
            return;
        }
        ServiceShareObject shareObject = ServiceShareObject.newInstance(id, shareTitle, sharePic, shareContent, shareUrl);
        shareDialogFragment = ShareDialogFragment.newInstance(shareObject, ShareChannelBuilder.TripShareChannel.TRIP_TYPE, MakeImageUtil.takeScreenShot(this));
        showDialogFragment(shareDialogFragment);
    }

    @Override
    public void onTopbarLeftPress() {
        finish();
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mTopbarMiddleAreaName = "";
        config.mTopbarRightAreaName = getString(R.string.clear_icon);
        config.mRightStyle = CustomUiConfig.AreaStyle.ICON_STYLE;
        return config;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mWebView) {
            mWebView.setVisibility(View.GONE);
            ViewGroup parent = (ViewGroup) mWebView.getParent();
            if (null != parent)
                parent.removeView(mWebView);
            mWebView.removeAllViews();
            mWebView.destroy();
            mWebView = null;
        }
    }


    public void initView() {
        ButterKnife.bind(this);
        mRefreshLayout.setEnabled(false);
        mTopbarLeftArea.setVisibility(View.GONE);
        if (shareCard != null) {
            shared = shareCard.isShared();
            shareTitle = shareCard.getTitle();
            shareContent = shareCard.getSubTitle();
            sharePic = shareCard.getBackPic();
            shareUrl = shareCard.getShareUrl();
            id = shareCard.getId();
            if (shared) {
                mTopbarRightArea.setText(getString(R.string.share_icon));
            } else {
                mTopbarRightArea.setText(getString(R.string.clear_icon));

            }
        }


        // 构建JS调用接口
        WebViewJsListener webViewJsListener = new WebViewJsListener() {
            @Override
            public void showToast(final String message) {
                mWebHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.toast(message);
                    }
                });
            }

            @Override
            public void setTitle(final String title) {
                mWebHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        updateTitle(title);
                    }
                });
            }

            @Override
            public void becomeInsider() {
                //已登录，跳转insider页面
                if (LoginInstance.getInstance().isLogin()) {
                    showLoading();
                    final CtUserInfo info = LoginInstance.getInstance().getUserInfo();
                    int type = info.isTravel() ? CtUserInfo.USER_FINDER : CtUserInfo.USER_TRAVEL;
                    info.setType(type);
                    Intent intent = new Intent(WebBrowserActivity.this, IndexActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    ServiceBusiness.getServiceList(new ApiProxy(new IProxyCallback() {
                        @Override
                        public boolean onProxyResult(ProxyResult<?> result) {
                            hideLoading();
                            CtApiResponse response = (CtApiResponse) result.getData();
                            if (response != null && response.code == CtResponseCode.RESULT_OK) {
                                if (response.result instanceof List) {
                                    List<ServiceInfo> serviceInfos = (List<ServiceInfo>) response.result;
                                    boolean isShow = ArrayUtil.isNullOrEmpty(serviceInfos) ? true : false;
                                    if (!info.isTravel() && isShow) {
                                        startActivity(new Intent(WebBrowserActivity.this, CreateTripGuideActivity.class));
                                    }
                                    LoginInstance.updateProfile(AppCoreRuntime.context, info, true);
                                }

                            }
                            return false;
                        }
                    }));


                } else {
                    //未登录，跳转登录页
                    LoginProxy.getInstance().gotoUserEnter(WebBrowserActivity.this);

                }
            }

        };
        WebViewMusicianJsInterface webViewMusicianJsInterface = new WebViewMusicianJsInterface(webViewJsListener);

        // 构建WebView配置WebSetting
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(false);
        // 开启用户缩放控制,默认载入时为显示全部
        webSettings.setBuiltInZoomControls(false);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        // 启用地理定位
        webSettings.setGeolocationEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setSupportMultipleWindows(true);
        webSettings.setPluginState(WebSettings.PluginState.ON);
        webSettings.setLoadsImagesAutomatically(true);

        // 配置WebView
    mWebView.addJavascriptInterface(webViewMusicianJsInterface,WebViewMusicianJsInterface.JS_INSIDER);


        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        mWebView.setBackgroundColor(0x00000000);
        mWebView.setWillNotCacheDrawing(false);
        mWebView.setWebViewClient(new

                                          WebViewClient() {

                                              @Override
                                              public boolean shouldOverrideUrlLoading(WebView webView, String url) {
                                                  boolean result = performShouldOverrideUrlLoading(webView, url);
                                                  // 已处理,关闭当前Web页面
                /*if (result) {
                    Jumper.finishActivity(WebBrowserActivity.this);
                }*/
                                                  return result;
                                              }

                                              @Override
                                              public void onPageStarted(WebView view, String url, Bitmap favicon) {
                                                  mRefreshLayout.setRefreshing(true);
                                                  mStateLayout.changeState(StateLayout.State.INIT);
                                                  super.onPageStarted(view, url, favicon);
                                              }

                                              @Override
                                              public void onPageFinished(WebView view, String url) {
                                                  mRefreshLayout.setRefreshing(false);
                                                  updateTitle(view.getTitle());
                                                  if (null != mWebView && mWebView.canGoBack()) {
//                    showCloseUI();
                                                  } else {
//                    hideCloseUI();
                                                  }
                                                  super.onPageFinished(view, url);
                                              }

                                              @Override
                                              public void onReceivedError(WebView view, int errorCode, String description, String
                                                      failingUrl) {
                                                  mStateLayout.changeState(StateLayout.State.NoNetwork);
                                                  mRefreshLayout.setRefreshing(false);
                                                  super.onReceivedError(view, errorCode, description, failingUrl);
                                              }

                                          }

        );
        mWebView.setWebChromeClient(new

                                            WebChromeClient() {

                                                @Override
                                                public void onReceivedTitle(WebView view, String title) {
                                                    updateTitle(title);
                                                    super.onReceivedTitle(view, title);
                                                }

                                                @Override
                                                public void onProgressChanged(WebView view, int newProgress) {
                                                    super.onProgressChanged(view, newProgress);
                                                }

                                                @Override
                                                public void onGeolocationPermissionsShowPrompt(String
                                                                                                       origin, GeolocationPermissions.Callback callback) {
                                                    callback.invoke(origin, true, false);
                                                }

                                                @Override
                                                public void onGeolocationPermissionsHidePrompt() {
                                                    super.onGeolocationPermissionsHidePrompt();
                                                }

                                                @Override
                                                public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message
                                                        resultMsg) {
                                                    WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
                                                    transport.setWebView(mWebView);
                                                    resultMsg.sendToTarget();
                                                    return true;
                                                }

                                            }

        );
        mWebView.setDownloadListener(new

                                             DownloadListener() {
                                                 @Override
                                                 public void onDownloadStart(String url, String userAgent, String contentDisposition, String
                                                         mimetype, long contentLength) {
                                                     if (!TextUtils.isEmpty(url)) {
                                                         Intent intent = new Intent(Intent.ACTION_VIEW);
                                                         intent.setData(Uri.parse(url));
                                                         Jumper.launchActivity(WebBrowserActivity.this, intent);
                                                     }
                                                 }
                                             }

        );
        mWebView.setOnTouchListener(new View.OnTouchListener()

                                    {
                                        @Override
                                        public boolean onTouch(View view, MotionEvent motionEvent) {
                                            if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                                                int tempScrollY = view.getScrollY();
                                                view.scrollTo(view.getScrollX(), view.getScrollY() + 1);
                                                view.scrollTo(view.getScrollX(), tempScrollY);  //返回原来位置，可不加
                                            }
                                            if (null != mWebView) {
                                                mWebView.requestFocus();
                                            }
                                            return false;
                                        }
                                    }

        );
        if (!showTitleBar)

        {
            mTopbar.setVisibility(View.GONE);
        } else

        {
            mTopbar.setVisibility(View.VISIBLE);
        }

    }



    public void initData() {
        load(mUrl);
    }


    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (null != mWebView && mWebView.canGoBack()) {
                mWebView.goBack();
                return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void onClick(View view) {

    }

    private void closeBrowser() {
        Jumper.finishActivity(this);
    }

    private boolean performShouldOverrideUrlLoading(WebView webView, String url) {
        AppLog.d(TAG + " performShouldOverrideUrlLoading url = " + url);
        boolean result = false;
        if (!TextUtils.isEmpty(url)) {
            Uri uri = Uri.parse(url);
            String schemeName = uri.getScheme();
            Scheme scheme = Scheme.getSchemeByName(schemeName);
            if (null != scheme) {
                if (scheme == Scheme.CUITRIP) {
                    result = SchemeUrlHandler.getInstance().dispatch(this, uri, webView);
                    // 判断是否需要Keep页面
                    /*String status = uri.getQueryParameter(SchemeParam.KEY_STATUS);
                    if (null != status && status.equals(SchemeParam.STATUS_KEEP_PAGE)) {
                        result = false;
                    }*/
                    result = true;
                }
            }
        }
        AppLog.d(TAG + " performShouldOverrideUrlLoading result = " + result);
        return result;
    }

    private void load(String url) {
        if (null != mWebView) {
            AppLog.d(TAG + " load url = " + url);
            setCookies();
            mStateLayout.changeState(StateLayout.State.Loading);
            if (com.lab.network.util.NetworkUtil.getConnectState(this) == com.lab.network.util.NetworkUtil.CONNECT_NONE) {
                mStateLayout.changeState(StateLayout.State.NoNetwork);
            } else {
                if (mStringObject != null) {
                    JSONObject jsonObject = JSONObject.parseObject(mStringObject);
                    Iterator<String> iterator = jsonObject.keySet().iterator();
                    StringBuilder urlParams = new StringBuilder();
                    while (iterator.hasNext()) {
                        String key = iterator.next();
                        if (urlParams.length() == 0 && !url.contains("?")) {
                            urlParams.append("?");
                        } else {
                            urlParams.append("&");
                        }
                        urlParams.append(key).append("=").append(jsonObject.getString(key));
                    }
                    mWebView.postUrl(url + urlParams.toString(), null);
                } else {
                    mWebView.loadUrl(url);
                }
            }

        }
    }

    private void reload() {
        if (null != mWebView) {
            AppLog.d(TAG + " reload");
            setCookies();
            mWebView.reload();
        }
    }

    private void setCookies() {
        try {
            CookieSyncManager.createInstance(this);
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.removeAllCookie();
            CookieSyncManager.getInstance().sync();
        } catch (Exception e) {
            AppLog.w(e.getMessage());
        } catch (Error e) {
            AppLog.w(e.getMessage());
        }
    }

    private void updateTitle(String title) {
        if (useWebTitle) {
            mTopbarMiddleArea.setText(this.webTitle);
        } else {
            mTopbarMiddleArea.setText(title);
        }
    }

    @Override
    public void finish() {
        ViewGroup view = (ViewGroup) getWindow().getDecorView();
        view.removeAllViews();
        super.finish();
    }

    private class WebHandler extends Handler {

        WeakReference<WebBrowserActivity> reference;

        public WebHandler(WebBrowserActivity activity) {
            reference = new WeakReference<WebBrowserActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            BaseActivity activity = reference.get();
            if (null == activity)
                return;
            switch (msg.what) {
            }
        }
    }

}
